package com.eve.xstream;

import com.eve.xstream.node.Result;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author: ivan.yao<haif.yao@gmail.com>
 * @date: 17/6/17.
 */
public class ResultMapConvertor implements Converter {

    private static final Logger logger = LoggerFactory.getLogger(ResultMapConvertor.class);

    @Override
    public boolean canConvert(Class clazz) {
        return clazz.equals(Result.class);
    }


    @Override
    public void marshal(Object o, HierarchicalStreamWriter hierarchicalStreamWriter, MarshallingContext marshallingContext) {
        logger.info("marshal this object:{}" ,o);
    }

    @Override
    public Object unmarshal(HierarchicalStreamReader reader,
                            UnmarshallingContext context) {
        Result result = new Result();
        if(reader.hasMoreChildren()) {
            while (reader.hasMoreChildren()) {
                reader.moveDown();
                final String nodeName = reader.getNodeName();
                result.put(nodeName, reader.getValue());
                reader.moveUp();
            }
        }
        return result;
    }
}
